package top.xiaoshuaila.searescue.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xiaoshuaila.searescue.mqtt.EmqClient;
import top.xiaoshuaila.searescue.mqtt.MqttProperties;
import top.xiaoshuaila.searescue.pojo.Tag;

import javax.annotation.PostConstruct;
import java.util.*;

@Service
public class MqttService {
    String pub="/sub0002/";
    String sub="/pub0002/";
    Float yuzhi=110000f;
    //查询全部
    String GetAllmsg=":01 04 00 00 00 1E DD"
            .replaceAll(" ","");
    //安全
    String Safemsg=":01 06 00 1C 00 04 D9"
            .replaceAll(" ","");
    //警告
    String Alertmsg=":01 06 00 1C 00 05 D8"
            .replaceAll(" ","");
    //危险
    String Dangermsg=":01 06 00 1C 00 06 D7"
            .replaceAll(" ","");
    public int[]arrid=new int[]{7,11,12};
    @Autowired
    private EmqClient emqClient;
    @Autowired
    private MqttProperties mqttProperties;
    @Autowired
    private Tag tag;

    public Set<Integer> lost=new HashSet<>();

    public Integer Taskmsg=0;


    @PostConstruct
    public void init(){
        emqClient.connect(
                mqttProperties.getUsername(),
                mqttProperties.getPassword());
        SubAll();
    }
    public void SubAll(){
        for(int i=0;i<arrid.length;i++) {
            System.out.println(sub+String.format("%03d",arrid[i]));
            emqClient.substribe(sub + String.format("%03d",arrid[i]), 1);
        }
    }
    public void PubAll(){
        for(int i=0;i<arrid.length;i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(arrid[i]==tag.getTAG()&&Taskmsg!=0)
            {
                if(Taskmsg==1)setSafe(tag.getTAG());
                else if(Taskmsg==2)setAlert(tag.getTAG());
                else if(Taskmsg==3)setDanger(tag.getTAG());
                Taskmsg=0;
            }
            else {
                System.out.println(pub+String.format("%03d",arrid[i])+"查询所有"+GetAllmsg);
                emqClient.publish(pub + String.format("%03d",arrid[i]),
                        GetAllmsg, 1, false);
            }
        }
    }
    public void setSafe(int id){
        System.out.println(pub+String.format("%03d",id)+"设为安全"+Safemsg);
        emqClient.publish(pub+String.format("%03d",id),Safemsg,1,false);
    }
    public void setAlert(int id){
        System.out.println(pub+String.format("%03d",id)+"设为警报"+Alertmsg);
        emqClient.publish(pub+String.format("%03d",id),Alertmsg,1,false);
    }
    public void setDanger(int id){
        System.out.println(pub+String.format("%03d",id)+"设为救援"+Dangermsg);
        emqClient.publish(pub+String.format("%03d",id),Dangermsg,1,false);
    }
}